package com.example.base.validation.component;


import com.example.base.validation.annation.IsMail;
import com.example.base.validation.utils.ValidatedUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class IsMailValidator implements ConstraintValidator<IsMail, String> {

    private boolean required = false;

    private boolean isRequiredNull=true;

    @Override
    public void initialize(IsMail constraintAnnotation) {
        required = constraintAnnotation.required();
        isRequiredNull=constraintAnnotation.isRequiredNull();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if(isRequiredNull){
            if(s==null || "".equals(s)){
                return false;
            }
        }else {
            if(s==null){
                return true;
            }
        }
        return ValidatedUtils.isMail(s);
    }
}
